package com.ddz.controller;

import com.ddz.service.GameRoomManager;
import com.ddz.model.User;
import com.ddz.util.StringUtil;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/trygame")
public class GameServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String contextPath = request.getContextPath();
        JSONObject jsonObject = new JSONObject();
        // 获取当前房间id
        String roomid = request.getParameter("roomid");
        if(StringUtil.isEmpty(roomid)||StringUtil.isOver100(roomid)||!StringUtil.isAlphaNumeric(roomid)){
            jsonObject.put("status", "fail");
            jsonObject.put("content", "请输入正确的房间号！");
        }
        else {
            // 判断房间当前是否未满
            if (GameRoomManager.getRoomPlayerCount(roomid) < 3 ||
                    GameRoomManager.Room_getinfo(roomid, "Status").isEmpty() ||
                    GameRoomManager.Room_getinfo(roomid, "Status").equals("waiting")) {
                jsonObject.put("status", "success");
                jsonObject.put("content", contextPath + "/game/game.jsp");
                // 设置用户所在的房间号
                User user = (User) request.getSession().getAttribute("User");
                user.setRoomid(roomid);
                System.out.println("玩家已加入房间：" + user);
                request.getSession().setAttribute("User", user);
            } else {
                jsonObject.put("status", "fail");
                jsonObject.put("content", "房间已满！");
            }
        }
        response.getWriter().write(jsonObject.toString());
    }

}
